package cn.txun.springboot61.controller;

import cn.txun.springboot61.entity.User;
import cn.txun.springboot61.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;

    //检查用户名可用
    @RequestMapping("/check")
    public int check(String username){
        //根据用户名查用户
        User user = userMapper.selectByName(username);
        if(user==null){
            return 1;//用户名可用
        }
        return 2;//用户名不可用
    }

    @RequestMapping("/reg")
    public int reg(User user){
        //根据用户名查用户
        User u = userMapper.selectByName(user.getUsername());
        if(u==null){//用户名可用
            userMapper.insert(user);
            return 1;
        }
        return 2;//用户名不可用
    }

    @RequestMapping("/login")
    public int login(User user, HttpSession session){
        User u = userMapper.selectByName(user.getUsername());
        if(u!=null){
            if(u.getPassword().equals(user.getPassword())){
                //把当前登录成功的用户信息保存到session会话对象中
                session.setAttribute("u",u);
                System.out.println(session.getAttribute("u"));
                return 1;//用户名和密码都正确
            }
            return 3;//密码不正确
        }
        return 2;//用户名不正确·
    }
    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        //从session对象中取出当前登录的用户对象并返回给客户端
        return (User)session.getAttribute("u");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        //删除登录成功时保存的用户对象
        session.removeAttribute("u");
    }


}
